package com.heqiang.spring.beans.factory.support;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.PropertyValue;
import com.heqiang.spring.beans.PropertyValues;
import com.heqiang.spring.beans.factory.*;
import com.heqiang.spring.beans.factory.config.AutowireCapableBeanFactory;
import com.heqiang.spring.beans.factory.config.BeanDefinition;
import com.heqiang.spring.beans.factory.config.BeanPostProcessor;
import com.heqiang.spring.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
             bean = createBeanInstance(name, beanDefinition, args);
             //填充属性
            applyPropertyValues(name,bean,beanDefinition);
            //执行bean初始化，并进行前置和后置处理
            bean = initializeBean(name,bean,beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        //注册实现了DisposableBean的bean对象
        registerDisposableBeanIfNecessary(name,bean,beanDefinition);

        //判断是否是单例的，如果是放在单例容器中
        if (beanDefinition.isSingleton()) {
            addSingleton(name, bean);
        }
        return bean;
    }

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        //不是单例的不执行销毁方法
        if (!beanDefinition.isSingleton()) {
            return;
        }
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdppter(beanName,bean,beanDefinition));
        }
    }

    protected Object createBeanInstance(String name, BeanDefinition beanDefinition,Object[] args) {
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructor = ctor;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition,name,constructor,args);
    }


    protected void applyPropertyValues(String beanName, Object bean,BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getProperValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                //判断bean的属性是都为bean对象，如果是，再递归getBean，拿到bean对象.
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getName());
                }
                //填充属性，可以用反射，这里用工具类，方便理解
                BeanUtil.setFieldValue(bean,name,value);
            }
        } catch (BeansException e) {
            throw new BeansException("",e);
        }
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

    private Object initializeBean(String beanName, Object bean,BeanDefinition beanDefinition) {

        if (bean instanceof Aware) {
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(this);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
        }
        //执行前置方法
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean,beanName);
        try {
            //待处理内容方法
            invokeInitMethods(beanName,wrappedBean,beanDefinition);
        } catch (Exception e) {
            throw new BeansException("初始化bean失败",e);
        }
        //执行后置方法
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean,beanName);

        return wrappedBean;
    }

    private void invokeInitMethods (String beanName, Object bean,BeanDefinition beanDefinition) throws Exception {
        if (bean instanceof InitializingBean) {
            ((InitializingBean) bean).afterPropertiesSet();
        }

        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            Method method = beanDefinition.getBeanClass().getMethod(initMethodName);
            if (method == null) {
                throw new BeanException("没有找到初始化方法"+initMethodName+"在这个bean里"+beanName);
            }
            method.invoke(bean);
        }
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existBean, String beanName) throws BeansException {
        Object result = existBean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postProcessBeforeInitialization(result, beanName);
            if (current == null){ return result;}
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existBean, String beanName) throws BeansException {
        Object result = existBean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postProcessAfterInitialization(result, beanName);
            if (current == null){ return result;}
            result = current;
        }
        return result;
    }
}
